package com.qingdai.usercenter.controller;

import com.qingdai.business.emuns.Coupon;
import com.qingdai.business.emuns.User;
import com.qingdai.business.emuns.UserRole;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.business.service.UserRoleService;
import com.qingdai.business.service.UserService;
import com.qingdai.business.utils.JwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.rmi.ServerException;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LiuZiMing
 * @since 2024-01-26
 */
@RestController
@RequestMapping("/user")
@Tag(name = "用户")
public class UserController {
    @Resource
    UserRoleService userRoleService;
    @Resource
    private UserService userService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private RedisTemplate redisTemplate;

    {
    }

    @GetMapping("/rock")
    @Operation(summary = "rocketMq测试", description = "")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    private CommonResult rocketMQ() throws MQClientException, UnsupportedEncodingException, MQBrokerException, RemotingException, InterruptedException {
        //构建消息
//        Message message = new Message("QingDai", "textMessage", JSON.toJSONBytes("msgData"));
        //发送同步消息
        SendResult sendResult = rocketMQTemplate.syncSend("QingDai:textMessage", "testMessage111111");

        return new CommonResult<>(200, "rocketMq测试", sendResult);
    }

    //获取所有用户
    @GetMapping("/all")
    @Operation(summary = "获取所有用户", description = "获取所有用户")
    public CommonResult getAllUser() {
        List<User> allCarts = userService.list();
        return new CommonResult(200, "获取所有用户成功", allCarts);
    }

    @GetMapping("/textMessage")
    @Operation(summary = "发送短信验证码", description = "发送短信验证码")
    @Parameters({
            @Parameter(name = "phoneNumber", description = "手机号", required = true),
    })
    public CommonResult sendTextMessage(String phoneNumber) throws ServerException {
        //如果redis缓存中存在手机号的验证码，说明验证码还未过期，可继续使用
        Object code = redisTemplate.opsForValue().get(phoneNumber);
        if (code != null) {
            return new CommonResult<>(400, phoneNumber + "验证码还没有过期，可继续使用！");
        }

        SendResult sendResult = rocketMQTemplate.syncSend("QingDai:textMessageCode", phoneNumber);

        return new CommonResult(200, "发送短信验证码成功");
    }

    //创建新用户
    @PostMapping("/")
    @GlobalTransactional
    @Operation(summary = "创建新用户", description = "创建新用户")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
            @Parameter(name = "name", description = "昵称", required = true),
            @Parameter(name = "username", description = "用户名", required = true),
            @Parameter(name = "password", description = "密码", required = true),
//            @Parameter(name = "remark", description = "备注信息", required = true),
            @Parameter(name = "phone", description = "手机号", required = true),
            @Parameter(name = "code", description = "验证码", required = true),
    })
    public CommonResult createUser(@RequestParam(required = true) String name,
                                   @RequestParam(required = true) String username,
                                   @RequestParam(required = true) String password,
//                                   @RequestParam(required = true) String remark
                                   @RequestParam(required = true) String phone,
                                   @RequestParam(required = true) Integer code
    ) {
        User hasUser = userService.getUserByUsername(username);
        if (hasUser != null) {
            return new CommonResult(400, "请重设用户名");
        } else {
            try {
                boolean userCreateResult = userService.save(new User(null, name, username, password, null, phone));
                if (!userCreateResult) {
                    throw new Exception("创建用户失败");
                }
            } catch (Exception exception) {
                return new CommonResult(400, "创建用户失败");
            }
            User user = userService.getUserByUsername(username);
            Integer userId = user.getId();
            try {
                boolean userRoleCreateResult = userRoleService.save(new UserRole(userId, 3));
                if (!userRoleCreateResult) {
                    throw new Exception("创建用户失败(用户权限设置失败)");
                }
            } catch (Exception exception) {
                return new CommonResult(400, "创建用户失败(用户权限设置失败)");
            }
            Integer codeSend = (Integer) redisTemplate.opsForValue().get(phone);
            if (code == null) {
                return new CommonResult(400, "请校验手机号");
            }
            if (!Objects.equals(code, codeSend)) {
                return new CommonResult(400, "验证码错误");
            }
            return new CommonResult(200, "创建用户成功,请登录");

        }

    }

    //根据jwt更新用户信息
    @PutMapping("/jwt")
    @Operation(summary = "更新用户", description = "更新用户")
    @Parameters({
            @Parameter(name = "name", description = "昵称", required = false),
            @Parameter(name = "username", description = "用户名", required = false),
            @Parameter(name = "password", description = "密码", required = false),
            @Parameter(name = "remark", description = "备注信息", required = false),
            @Parameter(name = "phone", description = "手机号", required = false),
    })
    public CommonResult updateUserByJwt(@RequestParam(required = false) String name,
                                    @RequestParam(required = false) String username,
                                    @RequestParam(required = false) String password,
                                    @RequestParam(required = false) String remark,
                                    @RequestParam(required = false) String phone,
                                    HttpServletRequest request
    ) {
        CommonResult result = jwtUtil.getAuthoritiesByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        User user = userService.getById(jwtUserId);
        if (user == null) {
            return new CommonResult(404, "根据令牌未找到用户");
        }
        User hasUser = userService.getUserByUsername(username);
        if (hasUser != null) {
            return new CommonResult(400, "请重设用户名");
        }
        boolean updateResult = userService.updateById(new User(jwtUserId, name, username, password, remark, phone));
        if (!updateResult) {
            return new CommonResult(400, "更新用户信息失败,请重试");
        }
        return new CommonResult(200, "更新用户信息成功");
    }

    //根据获取用户信息
    @GetMapping("/jwt")
    @Operation(summary = "获取用户", description = "() => 获取用户")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult getUserByJwt(HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        User user = userService.getById(jwtUserId);
        if (user == null) {
            return new CommonResult(404, "根据令牌未找到用户");
        }
        return new CommonResult(200, "根据令牌获取用户成功", user);
    }

    //根据jwt移除用户信息
    @DeleteMapping("/jwt")
    @Operation(summary = "移除用户", description = "() => 移除用户")
    @Parameters({
//            @Parameter(name = "id", description = "id", required = true),
    })
    public CommonResult deleteUserByJwt(HttpServletRequest request) {
        CommonResult result = jwtUtil.getUserIdByRequest(request);
        Integer jwtUserId = (Integer) result.getData();
        User user = userService.getById(jwtUserId);
        if (user == null) {
            return new CommonResult(404, "根据令牌未找到用户");
        }
        boolean removeResult = userService.removeById(jwtUserId);
        if (!removeResult) {
            return new CommonResult(200, "删除用户失败,请重试", user);
        }
        return new CommonResult(200, "删除用户成功", user);
    }

}
